package com.example.demo.service.impl;

import com.example.demo.entity.RegionStats;
import com.example.demo.service.COVID19MsgService;
import com.example.demo.utils.HttpSend;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * Author: wuhaoduan
 * Date: 2021/4/27 9:50
 */
@Service
public class COVID19MsgServiceImpl implements COVID19MsgService {

    @Value("${covid19-url}")
    private String url;

    List<RegionStats> regionStatsList = new ArrayList<>();

    @Override
    @PostConstruct
    @Scheduled(cron = "${updateCron}")
    public void getRegionStates() throws IOException {
        //清空
        regionStatsList.clear();

        //获得疫情resource文件
        Resource resource = HttpSend.GetVirusData(url);
        //获得疫情inputStreamReader文件流
        InputStreamReader reader = new InputStreamReader(resource.getInputStream(),"UTF-8");
        //解析csv文件
        CSVParser parser = CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord().parse(reader);
        try {
            for (final CSVRecord record : parser) {
                if(record != null){
                    String province = record.get("Province/State");
                    String country = record.get("Country/Region");
                    Integer newTotalCases = Integer.valueOf(record.get(record.size() - 1));
                    Integer addCases = newTotalCases - Integer.valueOf(record.get(record.size() - 2));
                    RegionStats regionStats = new RegionStats(province,country,newTotalCases,addCases);
                    regionStatsList.add(regionStats);
                }
            }
        } finally {
            reader.close();
            parser.close();
        }
    }

    //获得全部疫情数据
    @Override
    public List<RegionStats> getAllMsg(){
        return regionStatsList;
    }

    //获得搜索的对应国家、地区的疫情数据
    @Override
    public List<RegionStats> getMsgByCountry(String country,String state){
        return regionStatsList.stream()
                .filter((RegionStats item) -> {
                    if (!"".equals(country) && !country.equals(item.getCountry())) {
                        return false;
                    }
                    if (!"".equals(state) && !state.equals(item.getState())) {
                        return false;
                    }
                    return true;
                })
                .collect(Collectors.toList());

    }

}
